﻿// Inner Fire 游戏引擎库
// Lua绑定适配项目
//
// Copyright (c) 2025 by 尔西大帝. All rights reserved.
//
// 所属层级：应用层(4)
// 用于Assets的Lua绑定适配。
//
// Author: 尔西大帝
// Email: 2670613871@qq.com
// Created: 2025-04-30

#include "game/manager/game_manager.h"
#include "game/resource/assets.h"
#include "lua_manager.h"
#include <element.h>

namespace ifire::game {

static int Assets_GetAnimation(lua_State* L) {
  auto assets = L_THIS(Assets);
  const char* name = luaL_checkstring(L, 2);
  auto anime = assets->GetAnimation(name, true);
  ikit::lua_return_object(L, anime, "AnimationMeta");
  return 1; // 返回1个值
}

static int Assets_GetAnimationClip(lua_State* L) {
  auto assets = L_THIS(Assets);
  // 这里获得的名称是直接指定动画名和CLIP名。如果不指定CLIP，表示使用第一个。格式为[动画名:CLIP名]
  const char* name = luaL_checkstring(L, 2);
  ikit::str_element name_e(name);
  auto anime = assets->GetAnimation(name_e.name, true);
  if (anime == nullptr) {
    return lua_return_nil(L);
  }
  if (name_e.has_value()) {
    return ikit::lua_return_object(
        L, anime->FindClip(name_e.value), "AnimationClipMeta");
  } else {
    return ikit::lua_return_object(L, anime->First(), "AnimationClipMeta");
  }
}

static int Assets_GetAnimationBlend(lua_State* L) {
  auto assets = L_THIS(Assets);
  const char* name = luaL_checkstring(L, 2);
  auto anime = assets->GetBlend(name, true);
  ikit::lua_return_object(L, anime, "AnimationBlendMeta");
  return 1; // 返回1个值
}

static int Config_GetCharaAnimation(lua_State* L) {
  auto config = L_THIS(ConfigManager);
  auto item = config->GetCharaAnimation(L_STR(2));
  return ikit::lua_return_object(L, item, "CharaAnimationMeta");
}

void register_lua_assets(lua_State* L, LuaManager* lua_manager) {

  // 注册ASSETS
  luaL_Reg assets_methods[] = {                        //
      {"GetAnimation", Assets_GetAnimation},           //
      {"GetAnimationClip", Assets_GetAnimationClip},   //
      {"GetAnimationBlend", Assets_GetAnimationBlend}, //
      {NULL, NULL}};
  lua_register_metatable(L, "AssetsMeta", assets_methods);
  lua_set_global_object(
      L, lua_manager->GM()->GetAssets(), "Assets", "AssetsMeta");

  // 注册Config
  luaL_Reg config_methods[] = {                        //
      {"GetCharaAnimation", Config_GetCharaAnimation}, //
      {NULL, NULL}};
  lua_register_metatable(L, "ConfigManagerMeta", config_methods);
  lua_set_global_object(
      L, lua_manager->GM()->GetConfig(), "Config", "ConfigManagerMeta");
}
} // namespace ifire::game